package org.budo.html.editor.filter;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.html.editor.handler.BudoHtmlEditorHandler;
import org.budo.support.dao.page.Page;
import org.budo.support.dao.page.PageModel;
import org.budo.support.lang.util.ListUtil;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class BudoHtmlEditorFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServiceLoader<BudoHtmlEditorHandler> serviceLoader = ServiceLoader.load(BudoHtmlEditorHandler.class);
        Iterator<BudoHtmlEditorHandler> iterator = serviceLoader.iterator();
        List<BudoHtmlEditorHandler> editorHandlers = ListUtil.iteratorToList(iterator);

        boolean done = false;
        for (BudoHtmlEditorHandler editorHandler : editorHandlers) {
            if (editorHandler.handleRequest((HttpServletRequest) request, (HttpServletResponse) response, this)) {
                done = true;
                break;
            }
        }

        if (!done) {
            log.warn("#46 request=" + request + ", editorHandlers=" + editorHandlers);
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {}

    /**
     * 拿到上传的文件之后的处理，通常包括保存文件，写数据库
     * 
     * @return url
     */
    public String handleMultipartFile(MultipartFile multipartFile) {
        throw new RuntimeException();
    }

    /**
     * 查询文件列表，返回拼好的可访问的url地址
     * 
     * @return urls
     */
    public PageModel<String> listFile(Page page) {
        throw new RuntimeException();
    }
}